<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: sap<songaiping@hrbjjhh.com>
// +----------------------------------------------------------------------------

namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo 店铺模型
 */

class ShopModel extends BaseModel {

    /* 自动验证规则 */
    protected $_validate = array(
        array('shop_name', 'require', '店铺名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('shop_name', 'checkName', '店铺名称已经存在', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
    	array('shop_name', '1,15', '店铺名称长度不能超过15个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    	array('sort', 'number', '排序必须为数字', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),
    	array('sort', '1,5', '排序长度不能大于5个字符', self::VALUE_VALIDATE, 'length', self::MODEL_BOTH),
    	array('merchant_id', 'isMerchant', '必须选择商户', self::MUST_VALIDATE, 'function', self::MODEL_BOTH),
    	//array('shop_category_id', 'checkId', '必须选择店铺品类', self::MUST_VALIDATE, 'callback', self::MODEL_INSERT),
    	//array('conf_category_id', 'isConfCategory', '必须选择品类', self::MUST_VALIDATE, 'function', self::MODEL_BOTH),
    	
        
        array('shop_introduction', 'require', '请填写店铺介绍', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('shop_introduction', '1,150', '店铺介绍长度不能超过150个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('shop_address', 'require', '请填写店铺地址', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('shop_address', '1,25', '店铺地址长度不能超过25个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        
        array('logo_id', 'gtNumber', '请上传店铺logo图片', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
        array('cover_id', 'gtNumber', '请上传店铺封面图片', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
    	array('create_time', NOW_TIME, self::MODEL_INSERT),
    	array('update_time', NOW_TIME, self::MODEL_BOTH),
    	array('create_user_id', UID, self::MODEL_INSERT),
    	array('status', '1', self::MODEL_INSERT),
    );
    
    /**
     * 检测名称是否存在
     * @param  string $login_name 用户名
     * @return boolean          ture - 未重名，false - 已重名
     */
    protected function checkName($shop_name){
    	$shop_id = (int)I('shop_id');
    	//判断是否存在
    	$map = array();
    	if($shop_id != 0){
    		$map['shop_id'] = array('neq',$shop_id);
    	}
    	$map['shop_name'] = $shop_name;
    	$map['status'] = array('gt',-1);
    	if($this->where($map)->find()){
    		return false;
    	}
    	return true;
    }

    /**
     * 新增或更新一个店铺
     * @return boolean fasle 失败 ， int  成功 返回店铺ID
     * @author sap
     * @since 2015-8-17
     */
    public function update(){
        /* 获取数据对象 */
    	$data = $this->create($_POST);
        if(empty($data)){
            return false;
        }
        /* 添加或更新数据 */
        if(empty($data['shop_id'])){ //新增数据
            $shop_id = $this->add();
            if(!$shop_id){
                $this->error = '新增店铺出错！';
                return false;
            }
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新店铺出错！';
                return false;
            }else{
            	$shop_id = $data['shop_id'];
            }
        }
        S('sys_shop_',null);//清除缓存
        //内容添加或更新完成
        return $shop_id;
    }

    /**
     * 新增或更新一个店铺之后清除shopGoodsCategoryShop表中店铺品类关系
 	 * 并写入新的对应关系
     * @author cruise <jiangyu@hrbjjhh.com>
     * @since 2015-11-28
     */
    public function changeShopCategory($shop_id = 0,$goods_category_ids){
    	$shop_id = (int)$shop_id;
    	$goods_category_id = $goods_category_ids;
    	if(empty($shop_id)){
    		$this->error = '参数错误';
    	}
    	$object = M('shopGoodsCategoryShop');
    	$map['shop_id'] = $shop_id;
    	$check = $object->where($map)->select();
    	if($check != 0){
    		$delete = $object->where($map)->delete();
    		if($delete == 0){
    			$this->error = '数据清除失败';
    		}
    	}
    	$date_final = array();
    	foreach ($goods_category_id as $val){
    		$date_final[] = array(
    				'shop_id' => $shop_id,
    				'goods_category_id' => $val
    		);
    	}
    	$object->addAll($date_final);
    }
    
    /**
     * @todo 店铺详情
     * @param int $shop_id 店铺id
     * @param string $field 查询字段
     * @return false|array
     * @author sap
     */
    public function shopShow($shop_id=0,$field=''){
    	//获取数据
    	$shop_id = (int)$shop_id;
    	if($shop_id == 0){
    		$this->error = '请正确操作';
    		return false;
    	}
    	$map = array();//初始化查询条件
    	//查询条件
    	$map['shop_id'] = $shop_id;
    	$map['status'] = array('gt',-1);
    	//返回值
    	return $this->where($map)->field($field)->find();
    }
    
    /**
     * @todo 调取店铺列表
     * @author sap
     */
    public function getShopList($map = array(),$field='',$orderby='sort desc,shop_id desc'){
    	return $this->where($map)->field($field)->order($orderby)->select();
    }
    
    /**
     * @todo 调取店铺列表(视图列表)
     * @author sap
     */
    public function getShopActivityList($map = array(),$field='',$orderby='sort desc,shop_id desc'){
    	return D('ShopActivityView')->where($map)->field($field)->order($orderby)->select();
    }
    
    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     * @author PHP@妖孽 <mashengjie@hrbjjhh.com>
     */
    public function getPk(){
    	return 'shop_id';
    }
    
    /**
     * @todo 根据活动调取商户列表
     * @param int $activity_id
     * @author sap
     */
    public function getActivityMerchant($activity_id){
    	//获取
    	$activity_id = (int)$activity_id;
    	if($activity_id == 0){
    		return null;
    	}
    	//活动id大于0时获取绑定商户，小于0获取所有商户 fang update
    	if($activity_id > 0){
    	    //根据活动读取店铺
    	    $map = array();
    	    $map['activity_id'] = $activity_id;
    	    $shop_activity = M('ShopActivity')->where($map)->field('shop_id')->select();
    	    if(empty($shop_activity)){
    	        return null;
    	    }
    	    //根据店铺读取商户
    	    $shop_ids = implode(',',array_unique(array_column($shop_activity, 'shop_id')));//用户列表字符串
    	    $where = array();
    	    $where['shop_id'] = array('in',$shop_ids);
    	    $where['status'] = array('gt',-1);
    	    $shop_list = $this->getShopList($where,'merchant_id');
    	    if(empty($shop_list)){
    	        return null;
    	    }

    	    //根据商户读取商户名
    	    $merchant_array = array_unique(array_column($shop_list, 'merchant_id'));
    	    
    	    // 获取员工的商户权限（非开发者模式）
    	    if(IS_ROOT == false){
    	        $rules = M('auth_merchant')->where(array('member_id' => UID))->getField('rules');
    	        // 有商户权限设置的用户
    	        if($rules != ""){
    	            $allow_merchant = explode(',', $rules);
    	            $merchant_array = array_intersect($allow_merchant, $merchant_array);
    	        }
    	    }
    	    
    	    //fang 修改 0310
    	    $merchant_ids = implode(',', $merchant_array);//用户列表字符串
    	    $where_merchant = array();
    	    $where_merchant['merchant_id'] = array('in',$merchant_ids);
    	    
    	    
    	}
    	$where_merchant['status'] = array('gt',-1);
    	$merchant_list = D('Merchant','Service')->getMerchantList($where_merchant);
    	return $merchant_list;
    }
    
    /**
     * @todo 根据活动商户调取店铺（公共方法）不受权限控制
     * @param int $activity_id
     * @param int $merchant_id
     * @author sap
     */
    public function getMerchantShop($activity_id,$merchant_id){
    	//获取
    	$activity_id = (int)$activity_id;
    	$merchant_id = (int)$merchant_id;
    	if($activity_id == 0){
    		return null;
    	}
    	if($merchant_id == 0){
    		return null;
    	}
    	//读数据库
    	$map = array();
    	$map['merchant_id'] = $merchant_id;
    	$map['status'] = array('gt',-1);
    	//活动id大于0获取绑定商户下的店铺 fang update
    	if($activity_id > 0){
    	    $map['activity_id'] = $activity_id;
    	    return $this->getShopActivityList($map,'shop_id,shop_name');
    	}else{
    	    return $this->getShopList($map,'shop_id,shop_name');
    	}
    	
    }
    
    /**
     * @todo 判断品类下是否有店铺数据
     * @param string $conf_category_ids
     * @author sap
     */
    public function judgeConfCategoryShop($conf_category_ids=''){
    	if($conf_category_ids == ''){
    		$this->error='参数丢失，请重试';
    		return false;
    	}
    	$where['conf_category_id'] = array('in',$conf_category_ids);
    	$where['status'] = array('gt',-1);
    	$shop_list = $this->getShopList($where,'shop_id');
    	if(!empty($shop_list)){
    		$this->error = '品类下有店铺，无法删除';
    		return false;
    	}
    	return true;
    }
    
    /**
     * @todo 判断商户下是否有店铺数据
     * @param string $class_ids
     * @author sap
     */
    public function judgeMerchantShop($merchant_ids=''){
    	if($merchant_ids == ''){
    		$this->error = '参数丢失，请重试';
    		return false;
    	}
    	$where['merchant_id'] = array('in',$merchant_ids);
    	$where['status'] = array('gt',-1);
    	$shop_list = $this->getShopList($where,'shop_id');
    	if(!empty($shop_list)){
    		$this->error = '商户下有商铺，无法删除';
    		return false;
    	}
    	return true;
    }
    
    /**
     * @todo 验证店铺和商品品类关系
     * @param string $id
     * @author Cruise <jiangyu@hrbjjhh.com>
     * @return boolean
     */
    public function shopGoodsCategoryJudge($id){
    	$obj = M('ShopGoodsCategoryShop');
    	$map['shop_id'] = array('in',$id);
    	if(empty($id)){
    		$this-> error = '查询条件不正确';
    		return false;
    	}
    	$data = $obj->where($map)->field('goods_category_id')->find();
    	if($data){
    		$this-> error = '店铺与商品品类绑定，不允许删除';
    		return false;
    	}else{
    		return true;
    	}
    }
    
    /**
     * @todo 验证店铺和商品关系
     * @param string $id
     * @author Cruise <jiangyu@hrbjjhh.com>
     * @return boolean 
     */
    public function shopGoodsJudge($id){
    	$obj = M('ShopGoods');
    	$map['shop_id'] = array('in',$id);
    	$map['status'] = array('gt',-1);
    	if(empty($id)){
    		$this-> error = '查询条件不正确';
    		return false;
    	}
    	$data = $obj->where($map)->field('goods_id')->find();
    	if($data){
    		$this-> error = '店铺下有商品，请先删除商品！';
    		return false;
    	}else{
    		return true;
    	}
    }
    
    /**
     * @todo 验证店铺和店铺品类关系
     * @param string $id
     * @author Cruise <jiangyu@hrbjjhh.com>
     * @return boolean 
     */
    public function shopCategoryJudge($id){
    	$map['shop_id'] = array('in',$id);
    	if(empty($id)){
    		$this-> error = '查询条件不正确';
    		return false;
    	}
    	$data = $this->where($map)->field('shop_category_id')->find();
    	if($data['shop_category_id']){
    		$this-> error = '店铺与店铺品类绑定，不允许删除';
    		return false;
    	}else{
    		return true;
    	}
    }
    
    /**
     * @todo 检测商户品类是否选中
     * @param  string $id 商户品类id
     * @return boolean     ture - id成立，false - id无效
     */
    protected function checkId($id){
    	if($id == 0 || $id == ''){
    		return false;
    	}else{
    		return true;
    	}
    }
    
    /**
     * @todo 验证大于0的数字
     */
    public function gtNumber($pic_id){
        $pic_id = (int)$pic_id;
        if($pic_id <= 0){
            return false;
        }
    
    }
   
}
